<template>
  <FullCalendar ref="fullCalendar" class="demo-app-calendar" :options="calendarOptions">
    <template v-slot:eventContent="arg">
      <b>{{ arg.timeText }}</b>
      <i>{{ arg.event.title }}</i>
    </template>
  </FullCalendar>
  <calendar-edit ref="editRef" @upSuccess="upSuccess"></calendar-edit>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue'
import '@fullcalendar/core/vdom' // solve problem with Vite
import FullCalendar, {CalendarOptions, EventApi, EventClickArg} from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import listPlugin from '@fullcalendar/list'
import {getScheduleListApi, updateCalendarApi} from '@/api/schedule'
import CalendarEdit from "@/views/schedule/component/CalendarEdit.vue";
import {EditType} from "@/type/BaseEnum";
import dayjs from "dayjs";
import {message} from "ant-design-vue";

const fullCalendar = ref();
const editRef = ref();
//未添加数据的日历点击事件
const addClick = (selectInfo: any) => {
  // alert('新增事件')
  console.log(selectInfo)
  editRef.value.editCalender(EditType.ADD)
}

//日历编辑
const editClick = (clickInfo: EventClickArg) => {
  editRef.value.editCalender(EditType.EDIT,clickInfo.event.extendedProps);
}

//移动日历参数
const removeParam = reactive({
  id: '',
  beginTime: '',
  endTime: '',
  dateTime: ''
})
//拖动事件
const removeClick = async (item: EventClickArg) => {
  removeParam.id = item.event.id
  removeParam.dateTime = dayjs(item.event.start).format('YYYY-MM-DD');
  removeParam.beginTime = dayjs(item.event.start).format('HH:mm:ss');
  removeParam.endTime = dayjs(item.event.end).format('HH:mm:ss');
  let res = await updateCalendarApi(removeParam)
  if (res && res.code == 200) {
    message.success(res.msg)
    await getScheduleList()
  }else {
    message.error(res.msg)
  }
}


//上周
const prevWeekCustomClick = () => {
  fullCalendar.value.getApi().prev();
}
//下周
const nextWeekCustomClick = () => {
  fullCalendar.value.getApi().next()
}
//今天
const todayCustomClick = () => {
  fullCalendar.value.getApi().today();
  fullCalendar.value.getApi().getDate();
}
//上月
const prevMonthCustomClick = () => {
  fullCalendar.value.getApi().prev();
}
//下月
const nextMonthCustomClick = () => {
  fullCalendar.value.getApi().next()
}
//本月
const thisMonthCustomClick = () => {
  fullCalendar.value.getApi().today();
  fullCalendar.value.getApi().getDate();
}

//日历属性
const calendarOptions = reactive({
  plugins: [
    dayGridPlugin,
    listPlugin,
    timeGridPlugin,
    interactionPlugin // needed for dateClick
  ],
  // 自定义按钮
  customButtons: {
    prevWeekCustom: {
      text: '上周',
      click: function () {
        prevWeekCustomClick();
      }
    },
    nextWeekCustom: {
      text: '下周',
      click: function () {
        nextWeekCustomClick();
      }
    },
    todayCustom: {
      text: '本周',
      click: function () {
        todayCustomClick();
      }
    },
    prevMonthCustom: {
      text: '上月',
      click: function () {
        prevMonthCustomClick();
      }
    },
    nextMonthCustom: {
      text: '下月',
      click: function () {
        nextMonthCustomClick();
      }
    },
    thisMonthCustom: {
      text: '本月',
      click: function () {
        thisMonthCustomClick();
      }
    }
  },
  headerToolbar: {
    start: 'timeGridWeek,prevWeekCustom,todayCustom,nextWeekCustom',
    right: 'dayGridMonth,prevMonthCustom,thisMonthCustom,nextMonthCustom',
    center: 'title'
  },
  //修改headerToolbar的文字
  buttonText: {
    today: '今天',
    month: '月视图',
    week: '周视图',
    day: '日',
    list: '周列表'
  },

  //设置日历的高度
  contentHeight: window.innerHeight - 260,
  // 默认为那个视图（月：dayGridMonth，周：timeGridWeek，日：timeGridDay）
  initialView: 'timeGridWeek',
  // 切换语言，当前为中文
  locale: 'zh-cn',
  //月视图的显示模式，fixed：固定显示6周高；liquid：高度随周数变化；variable: 高度固定
  weekMode: 'liquid',

  // 设置一周中显示的第一天是哪天，周日是0，周一是1，
  firstDay: 1,
  // 时间轴间距
  slotMinTime: '07:00',
  slotMaxTime: '21:00',
  slotDuration: '00:' + 15,
  slotLabelFormat: {
    hour: 'numeric',
    minute: '2-digit',
    hour12: false
  },
  eventTimeFormat: {
    hour: 'numeric',
    minute: '2-digit',
    hour12: false
  },
  //日历数据
  events: [],
  //Event是否可以进行（拖动、缩放）修改
  editable: true,
  // 是否显示全天插槽
  allDaySlot: false,
  // 是否显示当前时间标记
  nowIndicator: true,
  //是否随浏览器窗口大小变化而自动变化
  handleWindowResize: true,
  // 日期否可点击
  navLinks: true,
  // 月视图，是否为指定周数高度
  fixedWeekCount: true,
  // 月视图，是否显示非本月日期
  showNonCurrentDates: false,
  //设置是否可被单击选中
  selectable: false,
  selectMirror: true,
  dayMaxEvents: true,
  weekends: true,
  //新增事件
   dateClick: addClick,
   eventClick: editClick,
   eventDrop: removeClick
} as CalendarOptions)

//日历获取参数
const calendarParam = reactive({
  roomIdList: [],
  courseIdList: [],
  teacherIdList: [],
  startDate: '',
  endDate: '',
  beginTime: '',
  endTime: '',
  duration: 0
})
//获取日历数据
const getScheduleList = async () => {
  let res = await getScheduleListApi(calendarParam);
  //组装日历数据
  if (res && res.code == 200 && res.data.length > 0) {
    //清空日历数据
    calendarOptions.events = [];
    for (let i = 0; i < res.data.length; i++) {
      //最基本的日历数据格式
      let obj = {
        id: '',
        title: '',
        start: '',
        end: '',
        backgroundColor: '',
        className: '',
        //编辑的时候，可以从该属性获取数据
        extendedProps: Object
      }
      let index = res.data[i].courseColor.indexOf('-')
      let color = res.data[i].courseColor.substring(index + 1, res.data[i].courseColor.length);
      let classes = res.data[i].courseColor.substring(0, index)
      obj.id = res.data[i].id
      obj.title = res.data[i].courseName + ' '
          + res.data[i].teacherName + ' '
          + res.data[i].roomName + ' '
          + res.data[i].roomAddress
      obj.start = res.data[i].dateTime + ' ' + res.data[i].beginTime
      obj.end = res.data[i].dateTime + ' ' + res.data[i].endTime
      obj.backgroundColor = color
      obj.className = classes
      obj.extendedProps = res.data[i]
      calendarOptions.events.push(obj)
    }
  }
}


const upSuccess = () => {
  getScheduleList()
}

onMounted(() => {
  getScheduleList()
})

defineExpose({
  getScheduleList
})
</script>

<style scoped lang="scss">
:deep(.fc-button-primary) {
  background-color: #1890ff !important;
  border-color: #fff !important;
}

:deep(.bgs1) {
  background: #FF7670 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs2) {
  background: #27ae60 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs3) {
  background: #1890ff !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs4) {
  background: #009688 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs5) {
  background: #5FB878 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs6) {
  background: #FF5722 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs7) {
  background: #7705f9 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs8) {
  background: #009688 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs9) {
  background: #4c03f4 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs10) {
  background: #f22d6f !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs11) {
  background: #f73838 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs12) {
  background: #3874f7 !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs13) {
  background: #e066ff !important;
  border-color: #fff !important;
  color: #fff !important;
}

:deep(.bgs14) {
  background: #ffb800 !important;
  border-color: #fff !important;
  color: #fff !important;
}
</style>
